package unique;

//import backup.*;
import java.io.*;
import java.net.*;
import java.util.LinkedList;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WebServer extends Thread {

    private FileHandler cardsList;
    private Socket client;
    private ServerSocket socket;
    private ExecutorService exec;
    private boolean fechaServidor = true;

    public WebServer(int port, String archive) throws Exception { //"archive.txt"
        exec = Executors.newCachedThreadPool();
        socket = new ServerSocket(port);
        cardsList = new FileHandler(archive);
    }

    @Override
    public void run(){
        while (fechaServidor) {
            //System.out.println("Servidor no ar. Aguardando requisições.");
            try {
                Socket reqSocket = socket.accept();
                ServerThread trat = new ServerThread(reqSocket, this);
                exec.execute(trat);
            } catch (IOException e) {
                System.out.println("Erro ao aceitar a requisição: " + e);
            }
        }
    }

    public boolean isFechaServidor() {
        return fechaServidor;
    }

    public unique.FileHandler getCardsList() {
        return cardsList;
    }

    public void setCardsList(unique.FileHandler cardsList) {
        this.cardsList = cardsList;
    }
    
    

    public void setFechaServidor(boolean fechaServidor) {
        this.fechaServidor = fechaServidor;
    }
    
    public void answerIndex() throws Exception {
        PrintStream ps = new PrintStream(client.getOutputStream());
        
        for (int i = 0; i < cardsList.getCardsList().size(); i++)
            ps.println(cardsList.getCardsList().get(i).toString());

        ps.println ("INDEX completed succesfully.");
    }
    
    public void remove (int id) {
        cardsList.removeCardById(id);
    }
    
    public void add (String token) {
        cardsList.addCard((token.split(" :: ")[1]));
    }
    
    // nem sei se estava comentado antes /:
    /*
    public void answer(String token) {
        try {
            
            if (token.split(" :: ")[0].equals("REMOVE")) answerRemove(token);
            else if (token.split(" :: ")[0].equals("ADD")) answerAdd (token);
            else if (token.split(" :: ")[0].equals("EDIT")) answerEdit (token);
            else answerIndex();

} catch (Exception ex) {
            Logger.getLogger(WebServer.class  

.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /**/
    
    //não é mais executável
    /*
    public static void main(final String argv[]) throws Exception {

        System.out.println("Iniciando o servidor...");

        WebServer servidor = new WebServer(6789, "archive.txt");

        servidor.run();

        System.out.println("Servidor finalizando.");

    }
    //*/

}
